package com.acxy.cms.servlet;

import com.acxy.ants.core.exception.TipException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-09-22
 */

@ServerEndpoint("/websocket/{userKey}")
public class WebSocketTips {

    private Logger logger = LoggerFactory.getLogger(WebSocketTips.class);

    private static ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap();

    //连接时执行
    @OnOpen
    public void onOpen(@PathParam("userKey") String userKey, Session session) throws IOException{
        sessionMap.put(userKey, session);
        logger.debug("新连接：{}", userKey);
    }

    //关闭时执行
    @OnClose
    public void onClose(){
        logger.debug("连接：{} 关闭");
    }

    //收到消息时执行
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        logger.debug("收到用户{}的消息{}", session, message);
        session.getBasicRemote().sendText("收到 "+session+" 的消息 "); //回复用户
    }

    //连接错误时执行
    @OnError
    public void onError(Session session, Throwable error){
        logger.debug("用户id为：{}的连接发送错误", session);
        error.printStackTrace();
    }

    public static void sendMessage(String userKey, String message) {
        try {
            Session session = sessionMap.get(userKey);
            if(session != null)
                session.getBasicRemote().sendText(message); //回复用户
        } catch (IOException e) {
            e.printStackTrace();
            throw new TipException("websocket 消息推送异常!");
        }
    }
}
